<template>
    <view class="content">
        <van-nav-bar left-arrow @click-left="onClickLeft" :border="false" title="登录" class="fixed_top" id="navBar">
        </van-nav-bar>

        <view class="top">

            <!-- <view v-if="!weixinIsow">
                <van-button type="primary" v-if="!checked" @click="gouxuan">微信一键登录</van-button>
                <van-button type="primary" open-type="getPhoneNumber" @getphonenumber="getPhoneNumbe2r"
                    v-else>微信一键登录</van-button>
            </view> -->
            <view class="image">
                <img src="https://17lelife-bucket.oss-cn-beijing.aliyuncs.com/WeChat-App-Picture/loginLogo.png" alt=""
                    style="" mode="widthFix">
            </view>

            <view class="middle">
                <van-button type="primary" v-if="!checked" @click="gouxuan">手机号快捷登录</van-button>
                <van-button type="primary" open-type="getPhoneNumber" @getphonenumber="getPhoneNumbe2r" v-else>手机号快捷登录</van-button>
            </view>

                
            <view class="bottom_b">
                <view class="agreement" @click="onChange">
                    <van-checkbox style="width: 16px" icon-size="12px" :value="checked" @change="onChange"
                        :label-disabled="true" use-icon-slot>
                        <image @click="onChange" slot="icon" class="checked-img"
                            :src="checked ? activeIcon : inactiveIcon" />
                    </van-checkbox>
                    <!-- <view>登录即代表您已了解</view> 
              <view class="href" id="secrectAgreement" @click="secrectAgreement">《登录政策》</view>-->

                    <view id="secrectAgreement">
                        <view>
                            <span>本人已阅读并同意</span>
                            <span class="href">《17乐生活用户协议》、</span> <span class="href">《17乐生活服务协议》</span> 和
                            <span class="href" @click="secrectAgreement">《17乐生活隐私政策》</span>
                        </view>
                    </view>
                </view>
                <view class="no-login" @click="onClickLeft">遇到问题？拨打客服电话 <span class="href" @tap="callPhone">0359-8755558</span></view>
            </view>
        </view>

        <van-toast id="van-toast" />
    </view>
</template>
<script>
import Toast from '@/wxcomponents/vant/toast/toast'
import { weixinLoginApi } from '@/api/login.js'
export default {
  data () {
      return {
          userInfo:{},
          userLocation:{},
          isDisabled: false,
          showpopup: false,
          showAction: false,
          weixinIsow: true,
          phone: '',
          disable: true, // 验证手机号码位数样式，不足11位时，按钮置灰
          password: '',
          isNewUser: true,
          checked: false,
          username: '',
          show: true,
          getSms: '获取验证码',
          identityId: '', // 角色id
          access_token: '',
          refreshToken:'',
          sessionId: '',
          role: '',
          wxcode: '',
          isSendMsg: false,
          code: '',
          inactiveIcon:
          'https://17lelife-bucket.oss-cn-beijing.aliyuncs.com/WeChat-App-Picture/notChecked1126.png',
          activeIcon:
         'https://17lelife-bucket.oss-cn-beijing.aliyuncs.com/WeChat-App-Picture/goodsChecked1126.png', 
          infoTypes: {
              NICKNAME: '昵称',
              AVATAR: '头像',
              PHONE: '手机号',
              LOCATION: '位置信息'
          }         
      }
  },
  onReady () {
  // 清除缓存
  // uni.clearStorage()
  },
  methods: {
      phoneLogin () {
          if (!this.checked) {
              Toast('请先勾选同意服务协议')
              return false
          }
          uni.navigateTo({
              url: '/pages/login/phoneLogin'
          })
      },
      onClickLeft () {
          uni.navigateBack({
              delta: 1
          })
      },
      gouxuan () {
          if (!this.checked) {
              Toast('请先勾选同意服务协议')
              return false
          }
      },


      getPhoneNumbe2r (e) {
          console.log(e.detail.code)
          console.log(e.detail)
          // 新增：处理用户拒绝授权的情况
          if (e.detail.errMsg === 'getPhoneNumber:fail auth deny') {
              this.showAuthGuide('需要获取手机号授权才能登录，请授权后重试')
              return
          }
          uni.login({
              provider: 'weixin',
              success: (loginRes) => {
                console.log(loginRes,'loginRes')
                  if (loginRes.code) {
                      // 获取到了临时登录凭证code，下一步可以用它去换取用户信息等
                      console.log('登录成功，临时登录凭证code:', loginRes.code);
                      this.wxcode=loginRes.code
                      this.getLogin(e.detail)
                  } else {
                      console.log('登录失败', loginRes);
                  }
              },
              fail: (err) => {
                  if (err.errMsg.includes('auth deny')) {
                      // 用户明确拒绝授权登录
                      console.log('用户拒绝微信登录授权');
                      // 可以在这里弹出提示框，告知用户授权的重要性
                      uni.showToast({
                          title: '请授权登录以使用完整功能',
                          icon: 'none',
                          duration: 2000
                      });
                      this.showAuthGuide('需要微信登录授权才能使用该功能，请授权后重试')
                  } else {
                      // 其他登录失败原因
                      console.error(err);
                  }
              }
          });

      },

    //登录接口
      getLogin(detail){
          if (detail.errMsg === 'getPhoneNumber:ok') {
              const params = {
                  encryptedData: detail.encryptedData,
                  code: this.wxcode,
                  iv: detail.iv,
              }
              this.recordCollection({
                  type: this.infoTypes.PHONE,
                  time: new Date().toISOString(),
                  source: '手机号快速验证'
              });
              weixinLoginApi(params).then((res) => {
                  if (res.code === 200) {
                      this.access_token = res.data.token
                      this.refreshToken = res.data.refreshToken
                      console.log('access_token', this.access_token)
                      uni.setStorage({
                          key: 'access_token',
                          data: this.access_token
                      })
                      uni.setStorage({
                          key: 'refreshToken',
                          data: this.refreshToken
                      })
                      // 拿到access_token等信息后，可进一步获取用户信息，包括头像
                      // this.getUserInfo(response.data.access_token, response.data.openid);
                      uni.navigateBack()

                  } else {

                  }
              })
          } else {
            console.log('获取手机号失败，错误信息：', detail.errMsg) // 新增打印
            if (detail.errMsg.includes('auth deny')) {
                this.showAuthGuide('需要获取手机号授权才能登录，请授权后重试')
            } else {
                Toast('获取手机号失败，请稍后重试')
            }
        }
      },

      // 信息收集记录方法
      recordCollection(info) {
          const collections = uni.getStorageSync('privacyCollection') || [];
          if (!collections.find(item => item.type === info.type)) {
              collections.push(info);
              uni.setStorageSync('privacyCollection', collections);
          }
      },
      // 新增：授权引导方法
      showAuthGuide(msg) {
          uni.showModal({
              title: '授权提示',
              content: msg,
              success: (res) => {
                  if (res.confirm) {
                      uni.openSetting({
                          success: (settingRes) => {
                              if (settingRes.authSetting['scope.userPhone']) {
                                  // 用户重新授权后重新尝试获取手机号
                                  this.getPhoneNumbe2r({ detail: { errMsg: 'getPhoneNumber:ok' } }) // 模拟重新触发
                              }
                          }
                      })
                  }
              }
          })
      },
    // //   获取用户信息
    //   getUserInfo(access_token, openid) {
    //     uni.getUserInfo({
    //           provider: 'weixin',
    //           withCredentials: true,
    //           success: (userInfoRes) => {
    //               console.log(userInfoRes.userInfo.avatarUrl); // 这里就是获取到的用户头像链接
    //               console.log(userInfoRes.userInfo.nickName); // 用户昵称等其他信息
    //               // 可以将获取到的用户信息保存到Vue组件的数据中，方便后续展示或使用
    //             //   this.userInfo = userInfoRes.userInfo;
    //               const userAvatar = res.userInfo.avatarUrl;  // 获取头像链接
    //               const userName = res.userInfo.nickName;  // 获取用户昵称
    //               console.log(userAvatar, userName);
    //           },
    //           fail: (err) => {
    //             if (err.errMsg === 'getUserInfo:fail auth deny') {
    //                 // 用户明确拒绝授权获取用户信息
    //                 console.log('用户拒绝授权获取用户信息');
    //                 // 弹出提示框，告知用户授权的重要性并引导用户重新授权
    //                 uni.showModal({
    //                     title: '授权提示',
    //                     content: '需要获取您的信息来提供更好的服务，是否重新授权？',
    //                     success: (modalRes) => {
    //                     if (modalRes.confirm) {
    //                         // 用户点击了确定，重新调用获取用户信息接口
    //                         this.getUserInfo(access_token, openid);
    //                     }
    //                     }
    //                 })
    //             } else {
    //                 // 其他获取用户信息失败原因
    //                 console.error(err);
    //             }
    //           }
    //       });
    //   },

    //   getUserProFile(){
    //     wx.getUserProfile({
    //         desc: '用于完善会员资料', // 描述获取用户信息的用途
    //         success: (res) => {
    //             console.log(res,'用户信息')
    //             console.log(res.userInfo.avatarUrl); // 用户头像链接
    //             console.log(res.userInfo.nickName); // 用户昵称
    //         },
    //         fail: (err) => {
    //             console.log(err);
    //         }
    //     });
    //   },

      // 获取用户位置
    //   async getUserLocation() {
        
    //     // 先检查用户是否授权了位置信息权限
    //     const {authSetting}=await wx.getSetting
    //     console.log(authSetting,'authSetting')
    //     wx.getLocation({
    //         type: 'wgs84',
    //         success: (locationRes) => {
    //             this.userLocation = `经度：${locationRes.longitude}，纬度：${locationRes.latitude}`
    //         },
    //         fail: (err) => {
    //             console.error('获取位置信息失败：', err)
    //         }
    //     })
    // },
      weixinLogin () {
          this.weixinIsow = false
      },
      weixinLogina () {
          this.weixinIsow = true
      },
  
      userAgreement () {
          console.log('用户协议')
          uni.navigateTo({
              url: '/pages/login/userAgreement'
          })
      },
      login () {
          if (!this.checked) {
              Toast('请先勾选同意服务协议')
              return false
          }

          if (!this.isSendMsg) {
              Toast('请先点击发送验证码')
              return false
          }

          this.doLogin()
      },
      secrectAgreement () {
          console.log('隐私协议')
          uni.navigateTo({
              url: '/pages/login/secrectAgreement'
          })
      },
   

      onChange (e) {
          if (e.target.id !== 'secrectAgreement') {
              this.checked = !this.checked
          }
      },
      callPhone() {
        wx.makePhoneCall({
            phoneNumber: '0359-8755558'
        })
    }
     
  }
}
</script>
<style lang="scss" scoped>
.content {
    overflow: hidden;
    display: flex;
    flex-direction: column;
    height: 100vh;
    background: url('https://17lelife-bucket.oss-cn-beijing.aliyuncs.com/WeChat-App-Picture/loginBg.png') no-repeat;
    background-size: 100%;
}
.top{
    padding: 0 24px;
    flex: 1;
    display:flex;
    flex-direction: column;
    overflow: hidden;
}


::v-deep .van-cell {
    border: none;
    border-radius: 8px;
    background-color: #F7F8FA;
    margin: 0;
    width: auto;
    height: 48px;
    padding: 0 16px;
}
::v-deep .van-hairline--top-bottom:after {
    border: none;
}

.agreement {
    // height: 44px;
    font-size: 24rpx;
    color: #111111;
    display: flex;
    align-items: flex-start;
}
// ::v-deep .van-button--info {
//     width: 100%;
//     height: 86rpx;
//     border-radius: 8px;
//     background: #1F6AFF;
// }
::v-deep .van-button--primary {
    width: 100%;
    height: 86rpx;
    font-size: 28rpx;
    border-radius:50rpx;
    background: #FF6203 !important;
    border: 1px solid #ff6203 !important;
}

::v-deep .van-count-down {
    display: inline;
    font-size: 14px;
    color: #98C4FF;
}

.href {
    color: #ff6203;
}
/* ::v-deep .van-checkbox{
      width: 12px;
  } */

.gray {
    color: gray;
}
::v-deep .van-button__text {
    // font-family: "PingFang SC";
    // font-style: normal;
    font-weight: bold;
    font-size: 16px;
}
.password {
    margin: 24px 0 12px;
}
.checked-img {
    height: 12px;
    width: 12px;
    margin-top: 4px;
}
button::after{
    border: none;
}
.button-hover{
    background-color: transparent;
}
.no-login{
    font-size: 24rpx;
    margin-bottom: calc(81rpx + env(safe-area-inset-bottom));
    line-height: 24rpx;
    color: #757980;
    text-align: center;
    margin-top: 75rpx;
}
// .image{
//     flex: 1;
//     display: flex;
//     align-items: center;
//     justify-content: center;
//     // margin: 24px 0;
//     text-align: center;
//     background-size: contain;
//     background: url("https://17lelife-bucket.oss-cn-beijing.aliyuncs.com/WeChat-App-Picture/loginLogo.png")no-repeat center;
//     width: 124rpx;
//     height: 124rpx;
// }
.image{
    display: flex;
    align-items: center;
    justify-content: center;
    text-align: center;
    margin: auto;
    width: 124rpx;
    height: 124rpx;
    img{
        width: 100%;
        height: auto;
    }
}
.middle{
    height: 80rpx;
}

.bottom_b{
    margin-top: 52rpx;
}
::v-deep .van-nav-bar {
    background-color: transparent !important;
}
::v-deep .van-icon {
    color: #242629 !important;
}
</style>
